package com.mashibing.Interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.mashibing.constant.TokenConstantsConfiguration;
import com.mashibing.dto.ResponseResult;
import com.mashibing.dto.TokenResult;
import com.mashibing.util.JwtUtils;
import com.mashibing.util.RedisPrefixUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;


public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");
        boolean result = true;
        String resultString = "";

        TokenResult tokenResult = JwtUtils.checkToken(token);
//        try {
//            tokenResult = JwtUtils.parseToken(token);
//        } catch (SignatureVerificationException e) {
//            // 签名错误
//            resultString = "token sign error";
//            result = false;
//        } catch (TokenExpiredException e) {
//            // token 过期
//            resultString = "token expired";
//            result = false;
//        } catch (AlgorithmMismatchException e) {
//            // 算法错误
//            resultString = "token algorithm error";
//            result = false;
//        } catch (Exception e) {
//            // 其他错误
//            resultString = "token invalid";
//            result = false;
//        }

        /**
         * 如果token 解析成功
         * 1、从redis中获取token
         * 2、对比
         *
         */
        if (tokenResult == null) {
            resultString = "assess token invalid";
            result = false;
        }else {
            /**
             * 从redis中获取token
             * 1、获取手机号和身份，生成前缀key
             * 2、获取token
             */
            String identity = tokenResult.getIdentity();
            String phone = tokenResult.getPhone();
            String tokenKey = RedisPrefixUtils.generateTokenKey(phone, identity, TokenConstantsConfiguration.ACCESS_TOKEN_TYPE);
            String redisToken = stringRedisTemplate.opsForValue().get(tokenKey);

            // 如果redis中无token记录 或者 提交的token和redis中的token不相等
            if ((StringUtils.isBlank(redisToken)) || !redisToken.trim().equals(token.trim())) {
                resultString = "assess token invalid";
                result = false;
            }
        }


//        如果token 未通过
        if (!result) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置响应状态为401
            response.setContentType("application/json;charset=UTF-8");
            // PrintWriter 对象，用于向客户端写入响应数据
            PrintWriter writer = response.getWriter();
            // writer.print 方法将 JSON 字符串写入响应
            writer.print(JSONObject.fromObject(ResponseResult.fail(resultString)).toString());
            // writer.flush 方法刷新 PrintWriter，确保所有数据都被写入到客户端
            writer.flush();
            return false; // 终止请求
        }

        // 如果 token 验证通过，继续执行请求
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
